package com.cyy.util

import java.util.ArrayList
import java.util.HashMap
import java.util.regex.Pattern


internal class ArrayProcessor(private val tree: PropertyTree) {

    fun apply(): PropertyTree {
        return process(tree)
    }

    private fun process(root: PropertyTree): PropertyTree {
        val result = PropertyTree()
        val entriesFromList = HashMap<String, List<Any>>()
        root.entries.forEach { entry ->
            val matcher = pattern.matcher(entry.key)
            if (matcher.find()) {
                val label = matcher.group(1)
                val index = Integer.parseInt(matcher.group(2))
                entriesFromList[label] = processListElement(entriesFromList[label], entry.value, index)
            } else {
                result.put(entry.key, getValue(entry.value))
            }
        }
        result.putAll(entriesFromList)
        return result
    }

    private fun processListElement(elements: List<Any>?, value: Any, index: Int): List<Any> {
        val result = elements?.let { ArrayList(it) } ?: ArrayList()
        adjustArray(index, result)
        result.add(index, getValue(value))
        return result.toArray().toList()
    }

    private fun getValue(value: Any): Any {
        return if (value is PropertyTree) process(value as PropertyTree) else value
    }

    private fun adjustArray(index: Int, elementList: MutableList<Any>) {
        if (elementList.size < index) {
            for (i in elementList.size until index) {
                elementList.add(i, "")
            }
        }
    }

    companion object {

        private val pattern = Pattern.compile("(.*)\\[(\\d+)\\]")
    }
}